import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbfdsys } from '../../../../atoms/db';


const logger = anylogger('pages/api/introduction/maintain/add.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = {
	picture: string;
}

/**
 * pages/api/introduction/maintain/add.api
 * 新增简介图片
 */
const handler = an48<Result>();

const key = 'pict';

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const { picture } = req.body as Message;
		if (typeof picture !== 'string') {
			res.status(200).json({
				ok: false,
				message: '缺少必要的参数'
			});
			return;
		};
		const r = await tbfdsys().first('*').where({
			key
		});
		if (r) {
			await tbfdsys().where({
				key
			}).update({
				value: picture
			});
			res.status(200).json({ ok: true });
			return;
		}
		await tbfdsys().insert({
			key,
			value: picture
		});
		res.status(200).json({ ok: true });
	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
